<!-- 耗量分析 -->
<template>
  <div class="flex-center table-top">
    <px-form ref="formRef" :model="queryParams" :inline="true" class="custom-form-ui search-form">
      <px-form-item label="设备编号" prop="eqpNo">
        <px-input v-model.trim="queryParams.eqpNo" style="width: 260px" placeholder="请输入设备编号" clearable />
      </px-form-item>
      <px-form-item label="气体种类" prop="type">
        <px-select v-model="queryParams.type" style="width: 260px" placeholder="请选择气体种类" clearable filterable>
          <px-option v-for="item in typeList" :key="item.value" :label="item.label" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="单位" prop="unit">
        <px-select v-model="queryParams.unit" style="width: 260px" placeholder="请选择单位" clearable filterable>
          <px-option v-for="item in unitList" :key="item.id" :label="item.name" :value="item.value" />
        </px-select>
      </px-form-item>
      <px-form-item label="日期" prop="date">
        <px-date-picker
          v-model="queryParams.date"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
          style="width: 260px"
        />
      </px-form-item>
      <div class="search-form-btn">
        <px-button type="primary" @click="handleQuery">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </div>
    </px-form>
  </div>
  <div class="table-top-btn">
    <px-checkbox v-model="checkAllVal" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</px-checkbox>
    <px-button
      v-has="`GAS_CONSUMPTION_SPECIALGAS_ANALYSIS_BTN`"
      style="margin-left: 8px"
      type="primary"
      plain
      :disabled="checkedList.length < 2"
      @click="toAnalysis"
      >分析</px-button
    >
  </div>
  <div v-loading="tableLoading">
    <px-checkbox-group v-if="tableData.length > 0" v-model="checkedList" @change="handleCheckedChange">
      <div ref="scrollbarBoxRef" class="chart-content-scrollbar">
        <px-scrollbar :height="scrollbarHeight">
          <div class="chart-content">
            <div v-for="(item, index) in tableData" :key="`${item.itemKey}${index}`" class="chart-bar">
              <div class="chart-name">
                <px-checkbox :label="item">
                  {{ item.itemName }}
                </px-checkbox>
              </div>
              <div :id="`chart${index}`" class="chart-container" />
            </div>
          </div>
        </px-scrollbar>
      </div>
    </px-checkbox-group>
    <div v-else class="empty-content">
      <px-empty description="暂无数据" />
    </div>
  </div>
  <!-- 分析 -->
  <div v-if="analysisVisible">
    <ChartAnalysis v-model:visible="analysisVisible" title="特气耗量分析" :units="units" :data="checkedList" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, toRefs, onMounted, onUnmounted, nextTick } from "vue";
import { queryDictData } from "@/api/common";
import { queryEquipSystem } from "@/api/equip/archive";
import { specialGasAnalysis } from "@/api/consumption/specialGas";
import ChartAnalysis from "../../component/chartAnalysis.vue";
import * as echarts from "echarts";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { formatMissingData } from "@/utils/common";

defineOptions({
  name: "GAS_CONSUMPTION_SPECIALGAS_ANALYSIS"
});

const units = [
  {
    label: "Psi"
  },
  {
    label: "Lbs"
  }
];

const formRef = ref(null);
const state = reactive({
  queryParams: {
    eqpNo: "",
    type: "",
    unit: "",
    date: ""
  },
  typeList: [],
  unitList: [],
  tableLoading: false,
  tableData: [],
  checkedList: [],
  checkAllVal: false,
  isIndeterminate: true,
  analysisVisible: false
});
const { queryParams, typeList, unitList, tableLoading, tableData, checkedList, checkAllVal, isIndeterminate, analysisVisible } = toRefs(state);

const gap = 40;
const defaultHeight = 620;
const scrollbarHeight = ref<number>(defaultHeight);
const scrollbarBoxRef = ref<HTMLElement | null>(null);

onMounted(async () => {
  getUnitList();
  getGasTypeList();
  handleQuery();
  await useUpdateDomHeight(scrollbarHeight, scrollbarBoxRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());

// 获取单位下拉框
const getUnitList = async () => {
  state.unitList = await queryDictData({ typeCode: "SPECIALTY_GAS_UNIT" });
};

// 获取气体种类下拉框
const getGasTypeList = async () => {
  const res = await queryEquipSystem({ className: "GAS" });
  // facCode   一期  FAC_83abf9   二期  FAC_93abf6
  const facCode = localStorage.getItem("facCode");
  const systemCode = facCode === "FAC_83abf9" ? "SCA6CC96" : facCode === "FAC_93abf6" ? "SCC3F1B9" : "";
  const t = res.find(item => item.code === systemCode);
  if (!t?.children?.length) return;
  state.typeList = t.children.map(item => {
    let { name, code } = item;
    const reg = new RegExp("供应系统", "g");
    name = name.replace(reg, "");
    return { label: name, value: code };
  });
  state.typeList = state.typeList.filter(item => item.label !== "辅助系统");
};

// 查询
const handleQuery = async () => {
  try {
    state.tableLoading = true;
    const { eqpNo, type, unit, date } = state.queryParams;
    const params = {
      itemKey: eqpNo,
      gasSystemCode: type,
      unit: unit,
      startDate: date === "" ? "" : date[0],
      endDate: date === "" ? "" : date[1]
    };
    state.tableData = await specialGasAnalysis(params);
    state.tableData.map((item, index) => {
      nextTick(() => {
        drawLineChart(item, index);
      });
    });
  } catch (err) {
    console.log(err);
  } finally {
    state.tableLoading = false;
  }
};

// 重置
const resetQuery = () => {
  formRef.value.resetFields();
  handleQuery();
};

const drawLineChart = (item, index) => {
  let myChart = echarts.init(document.getElementById(`chart${index}`));
  const min = value => {
    if (value.min < 0) {
      return Math.round(value.min * 1.5);
    } else {
      return 0;
    }
  };
  const max = value => {
    return Math.round(value.max * 1.5);
  };
  let option = {
    xAxis: {
      show: true,
      type: "category",
      data: item.valueList.map(v => v.name)
    },
    yAxis: {
      show: true,
      type: "value",
      name: item.unit,
      min,
      max
    },
    series: [
      {
        data: formatMissingData(item.valueList.map(v => v.num)),
        type: "line"
      }
    ]
  };
  nextTick(() => {
    myChart.setOption(option);
  });
};

const handleCheckAllChange = val => {
  state.checkedList = val ? state.tableData : [];
  state.isIndeterminate = false;
};

const handleCheckedChange = val => {
  state.checkAllVal = val.length === state.tableData.length;
  state.isIndeterminate = val.length > 0 && val.length < state.tableData.length;
};

const toAnalysis = () => {
  state.analysisVisible = true;
};
</script>

<style lang="scss" scoped>
@import url("@/views/gas/consumption/scss/common.scss");

.chart-content-scrollbar {
  width: 100%;
  // padding-right: 10px;
  // box-sizing: border-box;
  .chart-content {
    // height: calc(100vh - 330px);
    // overflow-y: auto;

    display: grid;
    grid-template-rows: 300px;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;

    // display: flex;
    // flex-wrap: wrap;
    // gap: 16px;
    width: 100%;
    padding-right: 10px;

    .chart-bar {
      // width: 514px;
      height: 300px;
      // margin-right: 12px;
      // margin: 0 16px 16px 0;
      border: 1px solid rgb(24 24 24 / 15%);
    }

    .px-scrollbar {
      width: 100%;
    }
  }
}

.chart-container {
  width: 100%;
  height: 270px;
}

.chart-name {
  width: 100%;
  height: 30px;
  line-height: 30px;
  text-align: center;
}

.empty-content {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: calc(100vh - 330px);
}

.table-top-btn {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

:deep(.px-empty__image) {
  display: none;
}

:deep(.px-empty) {
  height: calc(100vh - 330px);
  vertical-align: middle;
}
</style>
